package com.ifnoelse.scheduler;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created by ifnoelse on 2016/1/10.
 */
public class Scheduler {
    private ScheduledExecutorService executor;

    private List<Job> jobs = new ArrayList<>();

    public Scheduler(ScheduledExecutorService executor) {
        this.executor = executor;
    }

    public Job every(long interval){
        Job job = new Job(executor);
        job.setInterval(interval);
        jobs.add(job);
        return job;
    }
    public Job every(){
        return every(1);
    }

    public static void main(String[] args) {

        Scheduler scheduler = new Scheduler(Executors.newScheduledThreadPool(10));
        scheduler.every().second().task(()->{
            System.out.println(1);
        });

        scheduler.every(3).second().task(()->{
            System.out.println(3);
        });

        scheduler.start();
    }

    private void start() {
        for (Job job:jobs){
            executor.scheduleAtFixedRate(job.getTask(),job.getDelay(),job.getInterval(),job.getTimeUnit());
        }
    }
}
